package cl.gob.minvu.catastromobile;

import cl.gob.minvu.catastromobile.util.GenericUtil;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

/**
 * @author psep
 * 
 */
public class PhotoActivity extends AbstractActivity {

	private Button btnPhoto;
	private ImageView photo1;
	private Bitmap bitMap;
	private static int TAKE_PICTURE = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_photo);
		super.session = super.getSharedPreferences(GenericUtil.SESSION, MODE_PRIVATE);
		this.photo1 = (ImageView) super.findViewById(R.id.photo1);
		this.btnPhoto = (Button) super.findViewById(R.id.btnPhoto);
		this.validaCamara();
		this.onLoadSession();
	}

	/**
	 * Método que carga el objeto de sesión
	 */
	private void onLoadSession() {
		String object = super.session.getString(GenericUtil.PHOTO_1, null);

		if (object != null) {
			this.loadPhoto(object);
		}
	}

	/**
	 * @param bitPhoto
	 */
	private void loadPhoto(String bitPhoto) {
		this.bitMap = GenericUtil.stringToBitMap(bitPhoto);
		this.photo1.setImageBitmap(this.bitMap);
	}

	/**
	 * 
	 */
	private void validaCamara() {
		if (!this.hasCamera()) {
			this.btnPhoto.setEnabled(false);
		}
	}

	/**
	 * @return
	 */
	private boolean hasCamera() {
		return getPackageManager().hasSystemFeature(
				PackageManager.FEATURE_CAMERA);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.photo, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		
		if (id == R.id.photo_frm_descartar) {
			this.reset();
			return true;
		}
		
		return super.onOptionsItemSelected(item);
	}

	/**
	 * @param button
	 */
	public void onClick(View button) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(intent, TAKE_PICTURE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK
				&& intent != null) {
			Bundle extras = intent.getExtras();
			this.bitMap = (Bitmap) extras.get("data");
			this.photo1.setImageBitmap(this.bitMap);
			
			Editor edit = super.session.edit();
			edit.putString(GenericUtil.PHOTO_1, GenericUtil.bitmapToString(this.bitMap));
			edit.commit();
		}
	}

	@Override
	public void reset() {
		this.bitMap = null;
		this.photo1.setImageBitmap(null);
		Editor edit = super.session.edit();
		edit.remove(GenericUtil.PHOTO_1);
		edit.commit();
	}

	@Override
	public boolean validateFrm() {
		return false;
	}
}
